package com.trace.demo.controller;

import com.trace.demo.entity.DistributionInfo;
import com.trace.demo.entity.Order;
import com.trace.demo.repository.DistributionInfoRepository;
import com.trace.demo.repository.OrderRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/logistics")
public class LogisticsController {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private DistributionInfoRepository distributionInfoRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getLogistics(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String logisticsNumber,
            @RequestParam(required = false) String deliveryStatus) {

        try {
            // 从订单库中查询所有订单，不仅仅是有物流信息的订单
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
            
            // 这里简化为从订单信息中查询所有订单
            Page<Order> orderPage = orderRepository.findAll(pageable);
            
            // 转换订单为物流信息
            List<Map<String, Object>> logisticsList = new ArrayList<>();
            for (Order order : orderPage.getContent()) {
                Map<String, Object> logistics = new HashMap<>();
                logistics.put("id", order.getId());
                logistics.put("orderNumber", order.getOrderNumber());
                
                // 设置物流状态和相关字段
                String deliveryStatusValue;
                if (order.getTrackingNumber() != null && !order.getTrackingNumber().isEmpty()) {
                    // 已发货订单
//                    logistics.put("logisticsNumber", order.getTrackingNumber());
//                    logistics.put("logisticsCompany", order.getLogisticsCompany());
//                    logistics.put("shipDate", order.getShippingDate());
                    logistics.put("estimatedDeliveryDate", order.getShippingDate() != null ? 
                            order.getShippingDate().plusDays(2) : null);
                    logistics.put("actualDeliveryDate", order.getDeliveryDate());
                    
                    if (Order.OrderStatus.SHIPPED.equals(order.getStatus())) {
                        deliveryStatusValue = "运输中";
                    } else if (Order.OrderStatus.DELIVERED.equals(order.getStatus())) {
                        deliveryStatusValue = "已送达";
                    } else if (Order.OrderStatus.COMPLETED.equals(order.getStatus())) {
                        deliveryStatusValue = "已签收";
                    } else {
                        deliveryStatusValue = "已发货";
                    }
                    
                    // 设置其他字段
                    logistics.put("driverName", "配送员");
                    logistics.put("driverPhone", "13800138000");
                    logistics.put("vehicleNumber", "京A12345");
                    logistics.put("transportConditions", "常温运输");
                    
                } else {
                    // 未发货订单
                    logistics.put("logisticsNumber", "");
                    logistics.put("logisticsCompany", "");
                    logistics.put("shipDate", null);
                    logistics.put("estimatedDeliveryDate", null);
                    logistics.put("actualDeliveryDate", null);
                    deliveryStatusValue = "待发货";
                    
                    logistics.put("driverName", "");
                    logistics.put("driverPhone", "");
                    logistics.put("vehicleNumber", "");
                    logistics.put("transportConditions", "");
                }
                System.out.println("当前Shipping时间  "+order.getShippingDate());
                System.out.println(logistics.get("shipDate"));
                // 通用字段
                logistics.put("deliveryStatus", deliveryStatusValue);
                logistics.put("productName", order.getProductName() != null ? order.getProductName() : "未知产品");
//                logistics.put("startLocation", "发货仓库");
                logistics.put("destination", order.getShippingAddress() != null ? order.getShippingAddress() : "");


                Optional<DistributionInfo> byId = distributionInfoRepository.findById(order.getId());

                if(byId.isPresent()){
                    logistics.put("startLocation",byId.get().getStartLocation());
                    logistics.put("toLocation",byId.get().getToLocation());
                    logistics.put("logisticsNumber", byId.get().getLogisticsNumber());
                    logistics.put("logisticsCompany",byId.get().getLogisticsCompany());
                    logistics.put("shipDate",byId.get().getShipDate());
                }
                // 如果有指定状态筛选，则只添加符合条件的物流信息
                if (deliveryStatus == null || deliveryStatus.isEmpty() || deliveryStatusValue.equals(deliveryStatus)) {
                    logisticsList.add(logistics);
                }
            }
            for(int i=0;i<logisticsList.size();i++){
                System.out.println(logisticsList.get(i));
            }



            // 创建一个新的Page对象
            Page<Map<String, Object>> logisticsPage = new PageImpl<>(
                    logisticsList, 
                    pageable, 
                    orderPage.getTotalElements()
            );
            
            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("content", logisticsPage.getContent());
            response.put("totalElements", logisticsPage.getTotalElements());
            response.put("totalPages", logisticsPage.getTotalPages());
            response.put("size", logisticsPage.getSize());
            response.put("number", logisticsPage.getNumber());







            return ResponseEntity.ok(new ApiResponse<>(true, "物流信息获取成功", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取物流信息失败: " + e.getMessage(), null));
        }
    }


    @PostMapping("/insert")
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertLogistics(@RequestBody DistributionInfo distributionInfo) {
        try {

//                Optional<DistributionInfo> byId = distributionInfoRepository.findById(distributionInfo.getId());

                // 查询订单
                distributionInfo.setId(distributionInfo.getId());

                distributionInfo.setProductId(null);

                distributionInfo.setBatchId(String.valueOf(distributionInfo.getId()));

                distributionInfo.setBatchNumber("test");

                distributionInfoRepository.save(distributionInfo);




//            Optional<Order> orderOpt = orderRepository.findById(id);
//            if (!orderOpt.isPresent()) {
//                return ResponseEntity.status(HttpStatus.NOT_FOUND)
//                        .body(new ApiResponse<>(false, "未找到相关物流信息", null));
//            }
//
//            Order order = orderOpt.get();
//
//            // 转换为物流信息
//            Map<String, Object> logistics = new HashMap<>();
//            logistics.put("id", order.getId());
//            logistics.put("orderNumber", order.getOrderNumber());
//            logistics.put("logisticsNumber", order.getTrackingNumber());
//            logistics.put("logisticsCompany", order.getLogisticsCompany());
//            logistics.put("productName", order.getProductName());
//            logistics.put("shipDate", order.getShippingDate());
//            logistics.put("estimatedDeliveryDate", order.getShippingDate() != null ?
//                    order.getShippingDate().plusDays(2) : null);
//            logistics.put("actualDeliveryDate", order.getDeliveryDate());
//
//
//
//
//            // 设置物流状态
//            String deliveryStatusValue = "待发货";
//            if (Order.OrderStatus.SHIPPED.equals(order.getStatus())) {
//                deliveryStatusValue = "运输中";
//            } else if (Order.OrderStatus.DELIVERED.equals(order.getStatus())) {
//                deliveryStatusValue = "已送达";
//            } else if (Order.OrderStatus.COMPLETED.equals(order.getStatus())) {
//                deliveryStatusValue = "已签收";
//            }
//            logistics.put("deliveryStatus", deliveryStatusValue);
//
//            // 设置其他字段
//            logistics.put("driverName", "配送员");
//            logistics.put("driverPhone", "13800138000");
//            logistics.put("vehicleNumber", "京A12345");
//            logistics.put("transportConditions", "常温运输");
//            logistics.put("startLocation", "发货仓库");
//            logistics.put("destination", order.getShippingAddress());
//
//            Optional<DistributionInfo> byId = distributionInfoRepository.findById(order.getId());
//
//            if(byId.isPresent()){
//                logistics.put("startLocation",byId.get().getStartLocation());
//                logistics.put("toLocation",byId.get().getToLocation());
//            }

            return ResponseEntity.ok(new ApiResponse<>(true, "物流数据修改成功",null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "物流数据修改失败: " + e.getMessage(), null));
        }
    }



































    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getLogisticsById(@PathVariable Long id) {
        try {
            // 查询订单
            Optional<Order> orderOpt = orderRepository.findById(id);
            if (!orderOpt.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "未找到相关物流信息", null));
            }
            
            Order order = orderOpt.get();
            
            // 转换为物流信息
            Map<String, Object> logistics = new HashMap<>();
            logistics.put("id", order.getId());
            logistics.put("orderNumber", order.getOrderNumber());
            logistics.put("logisticsNumber", order.getTrackingNumber());
            logistics.put("logisticsCompany", order.getLogisticsCompany());
            logistics.put("productName", order.getProductName());
            logistics.put("shipDate", order.getShippingDate());
            logistics.put("estimatedDeliveryDate", order.getShippingDate() != null ? 
                    order.getShippingDate().plusDays(2) : null);
            logistics.put("actualDeliveryDate", order.getDeliveryDate());




            // 设置物流状态
            String deliveryStatusValue = "待发货";
            if (Order.OrderStatus.SHIPPED.equals(order.getStatus())) {
                deliveryStatusValue = "运输中";
            } else if (Order.OrderStatus.DELIVERED.equals(order.getStatus())) {
                deliveryStatusValue = "已送达";
            } else if (Order.OrderStatus.COMPLETED.equals(order.getStatus())) {
                deliveryStatusValue = "已签收";
            }
            logistics.put("deliveryStatus", deliveryStatusValue);
            
            // 设置其他字段
            logistics.put("driverName", "配送员");
            logistics.put("driverPhone", "13800138000");
            logistics.put("vehicleNumber", "京A12345");
            logistics.put("transportConditions", "常温运输");
            logistics.put("startLocation", "发货仓库");
            logistics.put("destination", order.getShippingAddress());

            Optional<DistributionInfo> byId = distributionInfoRepository.findById(order.getId());

            if(byId.isPresent()){
                logistics.put("startLocation",byId.get().getStartLocation());
                logistics.put("toLocation",byId.get().getToLocation());
                logistics.put("shipDate",byId.get().getShipDate());
                logistics.put("logisticsCompany", byId.get().getLogisticsCompany());
                logistics.put("logisticsNumber", byId.get().getLogisticsNumber());
            }

            return ResponseEntity.ok(new ApiResponse<>(true, "物流信息获取成功", logistics));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取物流信息失败: " + e.getMessage(), null));
        }
    }
    
    @PostMapping("/ship")
    public ResponseEntity<ApiResponse<Map<String, Object>>> shipOrder(@RequestBody Map<String, Object> shipData) {
        try {
            // 验证必要字段
            if (!shipData.containsKey("orderId")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "订单ID不能为空", null));
            }
            
            if (!shipData.containsKey("logisticsCompany") || !shipData.containsKey("logisticsNumber")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "物流公司和物流单号不能为空", null));
            }
            
            // 获取订单
            Long orderId = Long.valueOf(shipData.get("orderId").toString());
            Optional<Order> orderOpt = orderRepository.findById(orderId);
            if (!orderOpt.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "未找到相关订单", null));
            }
            
            Order order = orderOpt.get();
            
            // 更新订单状态和物流信息
            order.setStatus(Order.OrderStatus.SHIPPED);
            order.setShippingDate(LocalDateTime.now());
            order.setLogisticsCompany(shipData.get("logisticsCompany").toString());
            order.setTrackingNumber(shipData.get("logisticsNumber").toString());
            
            // 保存更新后的订单
            orderRepository.save(order);
            
            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("id", order.getId());
            response.put("orderNumber", order.getOrderNumber());
            response.put("logisticsCompany", order.getLogisticsCompany());
            response.put("logisticsNumber", order.getTrackingNumber());
            response.put("shipDate", order.getShippingDate());
            response.put("deliveryStatus", "运输中");
            
            return ResponseEntity.ok(new ApiResponse<>(true, "发货成功", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "发货失败: " + e.getMessage(), null));
        }
    }
    
    @GetMapping("/track/{logisticsNumber}")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> trackLogistics(@PathVariable String logisticsNumber) {
        try {
            // 模拟查询物流轨迹
            List<Map<String, Object>> trackData = new ArrayList<>();
            
            Map<String, Object> track1 = new HashMap<>();
            track1.put("time", LocalDateTime.now().minusHours(2).toString());
            track1.put("location", "北京市朝阳区");
            track1.put("status", "派送中");
            track1.put("description", "快件正在派送中，请保持电话畅通");
            trackData.add(track1);
            
            Map<String, Object> track2 = new HashMap<>();
            track2.put("time", LocalDateTime.now().minusHours(12).toString());
            track2.put("location", "北京市顺义区");
            track2.put("status", "到达");
            track2.put("description", "快件已到达北京转运中心");
            trackData.add(track2);
            
            Map<String, Object> track3 = new HashMap<>();
            track3.put("time", LocalDateTime.now().minusDays(1).toString());
            track3.put("location", "发货地");
            track3.put("status", "已发货");
            track3.put("description", "快件已被揽收，正在送往转运中心");
            trackData.add(track3);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "物流轨迹查询成功", trackData));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "查询物流轨迹失败: " + e.getMessage(), null));
        }
    }
    
    @GetMapping("/print/{id}")
    public ResponseEntity<byte[]> printShippingLabel(@PathVariable Long id) {
        try {
            // 模拟生成面单PDF
            // 在实际项目中，应该调用PDF生成服务，创建物流面单
            // 这里仅仅返回一个简单的文本信息
            String content = "这里是物流面单内容，订单ID: " + id;
            
            return ResponseEntity.ok()
                    .header("Content-Type", "application/pdf")
                    .header("Content-Disposition", "attachment; filename=\"shipping-label-" + id + ".pdf\"")
                    .body(content.getBytes());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }








} 